<template>
  <div class="box">
    <div class="header">
      <van-search
        v-model="keyword"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @input="onInput"
      >
      <template #left>
        <van-icon name="arrow-left" size="18" @click="$router.go(-1)"/>
      </template>
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    </div>
    <div class="content">

        <van-dropdown-menu>
          <van-dropdown-item v-model="priceVal" :options="priceOption" @change="priceSort"/>
          <van-dropdown-item v-model="salesVal" :options="salesOption" @change="salesSort"/>

          <van-dropdown-item title="筛选" ref="item">

            <h3>价格区间</h3>
            <van-cell center>
              <template #right-icon>
                <van-field v-model="min" placeholder="最低价"/>
                -
                <van-field v-model="max" placeholder="最高价"/>
              </template>
            </van-cell>

          <div style="padding: 5px 16px;">
            <van-button type="danger" block round @click="onConfirm">
              确认
            </van-button>
          </div>

        </van-dropdown-item>
      </van-dropdown-menu>

      <van-card
        v-for="item of list"
        :key="item.proid"
        :price="item.originprice"
        :desc="item.desc"
        :title="item.proname"
        :thumb="item.img1"
        @click="clickDetail(item)"
      />

          <!-- <Prolist :proList1="listPage" /> -->

    </div>
  </div>
</template>
<script>
import Vue from 'vue'
import { Field, Search, Icon, Toast, Card, DropdownMenu, DropdownItem, Cell, Switch, Button } from 'vant'
import { search } from '../../api/search'
import Prolist from '../../components/listPage.vue'

Vue.use(Field)
Vue.use(Search)
Vue.use(Icon)
Vue.use(Toast)
Vue.use(Card)
Vue.use(DropdownMenu)
Vue.use(DropdownItem)
Vue.use(Cell)
Vue.use(Switch)
Vue.use(Button)

export default {
  components: {
    Prolist
  },
  data () {
    return {
      min: '', max: '',
      num1: '',
      num2: '',
      keyword: '',
      priceVal: 0, // 价格
      salesVal: 0, // 销量
      switch1: false,
      switch2: false,
      priceOption: [
        { text: '默认排序', value: 0 },
        { text: '价格升序', value: 1 },
        { text: '价格降序', value: 2 }
      ],
      salesOption: [
        { text: '销量排序', value: 0 },
        { text: '销量升序', value: 1 },
        { text: '销量降序', value: 2 }
      ],
//---------------------------------------------
      keyword: '', // 搜索字段
      searchHistory: [], // 搜索历史
      listPage: [], // 遍历列表
      list: []  //升序，降序
    }
  },
  mounted () {
    
    // 搜索空字符，不向 localstroage 添加数据
    if(this.$route.params.keyword === ''){

    } 
    // 搜索非空字符
    else {

        // console.log(this.searchHistory.length);

        // 如果没有搜索记录
        if(localStorage.getItem('search') == null){
            // 新建一个 localstroage,往数组写入数据,存入 localstroage
            this.searchHistory.push(this.$route.params.keyword)
            localStorage.setItem('search',JSON.stringify(this.searchHistory))
        } else {  // 如果有搜索记录，获取出来

            this.searchHistory = JSON.parse(localStorage.getItem('search'))

            this.searchHistory.forEach((item, index) => {
              // console.log(item);   
              // 搜索到相同的字段删除，
              if(item === this.$route.params.keyword){
                this.searchHistory.splice(index,1)
              }
            })

            // 把新增的历史搜索写入 searchHistory 数组
            this.searchHistory.push(this.$route.params.keyword)
            // 把新的历史搜索 写入到 localstroge
            localStorage.setItem('search',JSON.stringify(this.searchHistory))
        }
    }

    //  将搜索页面的关键字传到搜索结果页面
    this.keyword = this.$route.params.keyword
    search ({count:1,limitNum:10,keyword:this.keyword}).then(res => {
        console.log(res.data.data);
        if (res.data.code === '10002') {
          Toast('暂未找到相关商品')
        } else {
          this.listPage = res.data.data
          this.list = JSON.parse(JSON.stringify(res.data.data))
          // console.log(this.listPage);  
        }
    })

  },
  methods: {

    clickDetail (item) {
      console.log(item);
      this.$router.push({ name: 'detail', params:{proid:item.proid}})
    },

    //  销量排序
    salesSort (val) {
      this.list = JSON.parse(JSON.stringify(this.listPage))
      if (val === 0) {
      
      } else if (val === 1) {
        this.list.sort((a,b) => {
          return a.sales - b.sales
        })
      } else {
        this.list.sort((a,b) => {
          return b.sales - a.sales
        })
      }
    },

    //  价格排序
    priceSort (val) {
      console.log(val);
      this.list = JSON.parse(JSON.stringify(this.listPage))
      if (val === 0) {
      
      } else if (val === 1) {
        this.list.sort((a,b) => {
          return a.originprice - b.originprice
        })
      } else {
        this.list.sort((a,b) => {
          return b.originprice - a.originprice
        })
      }
    },
    //  最大最小值筛选
    onConfirm () {
      // console.log(this.min,this.max);
      this.list = JSON.parse(JSON.stringify(this.listPage))
      // console.log(this.list);
      this.list = this.list.filter(item => {

        //  最大最小值都有输入
        if (this.min !== '' && this.max !== '') {

          return item.originprice > this.min && item.originprice < this.max

        } else if (this.min === '' && this.max !== '') {  // 只有最大值

          return item.originprice < this.max

        } else if (this.min !== '' && this.max === '') {  // 只有最小值

          return item.originprice > this.min

        }
      })
      this.$refs.item.toggle()
    },

    // 每输入会触发
    onInput (val) {
      this.keyword = val
    },
    // 点击搜索
    onSearch () {
      //  搜索字段 this.keyword
      
        // 搜索空字符
        if(this.keyword === ''){

        } else {
            // 在搜索结果页面 搜索历史记录为空，新增localstroage
            if(localStorage.getItem('search') == null){
                this.searchHistory.push(this.keyword)
                localStorage.setItem('search',JSON.stringify(this.searchHistory))
            } else {

                this.searchHistory = JSON.parse(localStorage.getItem('search'))

                this.searchHistory.forEach((item, index) => {   
                  // 搜索到相同的字段删除，
                  if(item === this.keyword){
                    this.searchHistory.splice(index,1)
                  }
                })
                // 把新增的历史搜索写入 searchHistory 数组
                this.searchHistory.push(this.keyword)
                // 把新的历史搜索 写入到 localstroge
                localStorage.setItem('search',JSON.stringify(this.searchHistory))
            }
        }
        search ({count:1,limitNum:10,keyword:this.keyword}).then(res => {
          console.log(res.data.data);
          if (res.data.code === '10002') {
            Toast('暂未找到相关商品')
          } else {
            this.listPage = res.data.data
          }
        })
    }
  }
}
</script>
<style lang="stylus" scoped>
.van-search
  padding 5px 12px
.van-search__content
  margin-left 12px
  border-radius 20px
.van-search__action
  color white
  background red
  border-radius 5px
  margin-left 10px
h3
  text-align center
  font-weight normal
  margin-top 10px
  font-size 20px
</style>
